<template>
  <div class="Application">
    <div class="page-title">
      <appli-tab v-if="group_id" :tabs="appTabs" :group_id="group_id" @activeIndex="activeIndex" />
    </div>
    <div class="page-head">
      <div class="page-tool between-wrap">
        <div class="between-start">
          <el-select
            v-model="state"
            placeholder="审核状态"
            class="tool-sel"
            clearable
          >
            <el-option
              v-for="item in appStatuses"
              :key="item.key"
              :value="item.key"
              :label="item.value"
            ></el-option>
          </el-select>
          <el-select
            v-model="modelName"
            placeholder="适配机型"
            class="tool-sel"
            clearable
          >
            <el-option
              v-for="item in modelSel"
              :key="item.model_id"
              :label="item.name"
              :value="item.model_id"
            ></el-option>
          </el-select>
          <search-input placeholder="应用名称" @search="searchChange" />
        </div>
        <!-- <div type="primary" class="tool-btn" @click="appSync">同步</div> -->
        <div class="between-end">
          <div v-if="$permiss(btnPermiss, '类别管理')" type="primary" class="tool-btn" @click="jump">类别管理</div>
          <div
            type="primary"
            class="tool-btn"
            v-if="$permiss(btnPermiss, '新增应用')"
            @click="open('add')"
          >
            新增应用
          </div>
        </div>
        

      </div>
    </div>
    <div class="page-body">
      <div class="media-list">
        <el-scrollbar class="scroll-bar">
          <el-row>
            <el-col v-for="(item, i) in list" :key="item.app_gid" :span="4">
              <div class="media-box">
                <div class="media-con app-con" @click="toDetail(item)">
                  <div class="media-pic app-pic">
                    <img :src="item.icon" />
                  </div>

                  <div
                    class="status app-status"
                    :class="
                      appStatuses.find((s) => s.key === item.status).className
                    "
                  >
                    {{ appStatuses.find((s) => s.key === item.status).value }}
                  </div>

                  <el-tooltip
                    effect="dark"
                    :content="item.name"
                    placement="left"
                  >
                    <div class="media-name">
                      {{ item.name }}
                    </div>
                  </el-tooltip>
                  <div class="media-row">
                    <div class="key">上传人</div>
                    <el-tooltip
                      effect="dark"
                      :content="item.user_name"
                      placement="left"
                    >
                      <div class="val">
                        {{ item.user_name }}
                      </div>
                    </el-tooltip>
                  </div>
                  <div class="media-row">
                    <div class="key">备注</div>
                    <el-tooltip
                      effect="dark"
                      :content="item.remark"
                      placement="left"
                    >
                      <div class="val">
                        {{ item.remark }}
                      </div>
                    </el-tooltip>
                  </div>
                </div>
                <div class="media-foot">
                  <div
                    v-if="$permiss(btnPermiss, '绑定')"
                    class="txt-btn spe-btn primary"
                    @click="openSelect(item)"
                  >
                    绑定
                  </div>
                  <div
                    class="txt-btn spe-btn primary"
                    v-if="$permiss(btnPermiss, '修改')"
                    @click="open('edit', item)"
                  >
                    修改
                  </div>
                  <div
                    class="txt-btn spe-btn error"
                    v-if="$permiss(btnPermiss, '删除')"
                    @click="doDelete(item)"
                  >
                    删除
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-scrollbar>
      </div>
    </div>

    <!-- 新增和修改弹框 -->
    <el-dialog
      :visible.sync="model.visible"
      width="450px"
      :title="model.type === 'add' ? `新增应用` : `修改应用`"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="dialog-body">
        <el-form
          ref="form"
          :model="form"
          label-width="90px"
          label-position="left"
        >
          <el-form-item label="应用名称" class="required">
            <el-input
              placeholder="请输入名称"
              v-model="form.name"
              name="appName"
              v-validate="'required|maxLength32'"
            />
            <div v-show="errors.has('appName')" class="el-form-item__error">
              {{ errors.first("appName") }}
            </div>
          </el-form-item>
          <!-- <el-form-item label="对象">
            <el-radio-group v-model="form.visibility">
              <el-radio v-for="item in visibilitys" :key="item.key" :label="item.key">{{item.value}}</el-radio>
            </el-radio-group>
            <el-select
              v-show="form.visibility == 1"
              v-model="form.organizations"
              name="organizations"
              placeholder="请选择客户"
              v-validate="'required'"
            >
              <el-option
                v-for="item in orgSel"
                :key="item.org_id"
                :value="item.org_id"
                :label="item.name"
              />
            </el-select>
            <div v-show="errors.has('organizations')" class="el-form-item__error">{{ errors.first('organizations') }}</div>
          </el-form-item> -->
          <el-form-item
            v-if="isShowHTML"
            label="内嵌html"
            class="upload-form-item required"
          >
            <el-input
              placeholder="请输入内嵌html"
              v-model="form.html"
              name="html"
              v-validate="'required|html'"
              maxlength="964"
            />
            <div v-show="errors.has('html')" class="el-form-item__error">
              {{ errors.first("html") }}
            </div>
          </el-form-item>
          <el-form-item label="应用图标" class="required">
            <el-upload
              v-validate="'required'"
              v-model="form.icon"
              name="icon"
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :http-request="uploadReq"
              :accept="imgAccept"
            >
              <img
                v-if="form.icon"
                key="pic"
                :src="form.icon"
                class="upload-img"
              />
              <img
                v-else
                key="default"
                src="~assets/img/upload.png"
                class="upload-img"
              />
            </el-upload>
            <div v-show="errors.has('icon')" class="el-form-item__error">
              {{ errors.first("icon") }}
            </div>
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" maxlength="128" v-model.trim="form.remark" />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="close">取 消</el-button>
        <el-button type="primary" @click="submit">保 存</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :visible.sync="visibility"
      width="430px"
      height="100px"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="dialog-content comfirm-body">
        <img class="comfirm-ico" src="~assets/img/warning.png" />
        <div class="comfirm-txt">
          <div v-if="[0, 1, 2, 4].includes(deleteStatus)">确定删除应用？</div>
          <div v-else>该应用已被上架，是否确定要删除?</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="visibility = false">取 消</el-button>
        <el-button type="primary" @click="appDelete">确 定</el-button>
      </span>
    </el-dialog>

    <application-select
      v-if="selectVisable"
      @cancel="appCancel"
      :resource_ids="resource_ids"
      @sure="appSure"
    />
  </div>
</template>

<script>
import { Loading } from "element-ui";
import { mapState } from "vuex";
import * as api from "@/api";
import { imgAccept } from "@/consts/consts";
import { appStatuses, visibilitys } from "@/consts/codesMap";
import { applicationFormKey } from "@/consts/formKey";
import client from "@/utils/oss";
import appliTab from "../../components/libs/appliTab.vue";

export default {
  components: { appliTab },
  data() {
    return {
      btnPermiss: [],
      imgAccept,
      list: [],
      state: "",
      modelName: "",
      search: "",
      appStatuses,
      visibilitys,
      model: {
        type: "add",
        visible: false,
      },
      form: {
        ...applicationFormKey,
      },
      app_id: "",
      orgSel: [],
      modelSel: [],
      visibility: false,
      appTabs: [],
      group_id: "",
      selectVisable: false,
      uploadFile: null,
      type: "",
      resource_idList: [],
      resource_select: [],
      resource_ids: [],
      isHasPermission: {
        addChecked: true,
        editChecked: true,
        deletChecked: true,
      },
      curTab: "", //当前tabs
      isShowHTML: false, //默认不显示URL
      deleteStatus: null,
      loading: null,
    };
  },
  computed: {
    ...mapState(["currentAppTab"]),
  },
  watch: {
    //状态
    state() {
      this.offset = 0
      this.applicationList();
    },
    modelName() {
      this.offset = 0
      this.applicationList();
    },
  },

  methods: {
    toDetail(item) {
      sessionStorage.setItem("application", JSON.stringify(item));
      this.$router.push(`/appDetail/${item.app_id}`);
    },

    open(type, row = null) {
      this.$validator.reset();
      this.isShowHTML = this.curTab === "独立应用";
      this.model.type = type;
      this.type = type;
      if (row) {
        for (const k in applicationFormKey) {
          this.form[k] = row[k];
        }
        this.app_id = row.app_id;
      }
      this.model.visible = true;
    },

    searchChange(e) {
      this.offset = 0
      this.search = e;
      this.applicationList();
    },

    fileChange(e) {
      let file = this.$refs.fileInput.files[0];
    },

    jump() {
      this.$router.push(`/category/appType`);
    },

    doSync() {
      this.$notify.closeAll();
      this.$notify({
        title: "成功",
        message: "同步成功",
        type: "success",
      });
    },

    handleAvatarSuccess(res, file) {
      this.form.imageUrl = URL.createObjectURL(file.raw);
    },

    beforeAvatarUpload(file) {
      const typeOk = ['image/png', 'image/PNG', 'image/jpg', 'image/JPG', 'image/jpeg', 'image/JPEG'].includes(file.type)
      if (typeOk) {
        this.uploadFile = file;
        return true;
      } else {
        return this.$message.warning('只支持png、jpg格式的图片')
      }
    },

    activeIndex(item) {
      sessionStorage.setItem('appCurTab', JSON.stringify(item))
      this.curTab = item.value;
      this.group_id = item.key;
      this.applicationList();
    },

    async uploadReq() {
      let [n, suf] = this.uploadFile.name.split(".");
      let fileName = `${n}_${+new Date()}.${suf}`;
      this.loading = Loading.service({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      let result = await client.put(`app/${fileName}`, this.uploadFile);

      if (result) {
        this.form.icon = result.res.requestUrls[0];
        this.loading.close();
      }
    },

    close() {
      this.model.visible = false;
      this.form = { ...applicationFormKey };
    },

    submit() {
      this.$validator.validateAll().then((valid) => {
        if (valid) {
          this.addOrEdit();
        } else {
          this.$message.warning("有信息未填写正确");
        }
      });
    },

    doDelete(item) {
      console.log(item, "item-----");
      this.deleteStatus = item.status;
      this.app_id = item.app_id;
      this.visibility = true;
    },
    getImgPath(i) {
      return `/manage/apps/${i}.png`;
    },
    openSelect(item) {
      this.resource_ids = item.resources;
      this.app_id = item.app_id;
      this.selectVisable = true;
    },
    appCancel() {
      this.selectVisable = false;
    },

    appSure(data) {
      this.resource_select = data;
      this.appBind();
    },
    // 应用分组
    async appGroupList() {
      const { code, data, total } = await api.category(this).appGroupList({
        offset: 0,
        limit: -1,
      });
      if (code === 0) {
        this.appTabs = data.map((el) => {
          return {
            key: el.app_gid,
            value: el.name,
          };
        });
        this.total = total;
        let appCurTab = sessionStorage.getItem('appCurTab')
        let tab = appCurTab ? JSON.parse(appCurTab) : this.appTabs[0]

        this.group_id = tab.key;
        this.curTab = tab.value;
        this.applicationList();
      }
    },

    async modelList() {
      const { code, data } = await api.dropdown(this).modelList();
      if (code === 0) {
        this.modelSel = data;
      }
    },

    // 资源同步
    async appSync() {
      const { code } = await api.application(this).appSync();
      if (code === 0) {
        this.doSync();
      }
    },

    async organizationList() {
      const { code, data } = await api.dropdown(this).organizationList();
      if (code === 0) {
        this.orgSel = data;
      }
    },

    // 应用列表
    async applicationList() {
      const { code, data } = await api.application(this).applicationList({
        group_id: this.group_id,
        model: this.modelName,
        name: this.search,
        state: this.state,
      });
      if (code === 0) {
        this.list = data;
      }
    },

    async addOrEdit() {
      let fn = this.model.type === "add" ? "appAdd" : "appUpdate";
      // 造数据
      this.form.group_id = this.group_id;
      const { code } = await api.application(this)[fn](this.form, this.app_id);
      if (code === 0) {
        this.$message.success("操作成功");
        this.close();
        this.applicationList();
      }
    },

    async appBind() {
      const p = {
        resource_ids: this.resource_select.map((item) => item.res_id),
      };
      const { code } = await api.application(this).appBind(p, this.app_id);
      if (code === 0) {
        this.$message.success("操作成功");
        this.app_id = "";
        this.applicationList();
        this.selectVisable = false;
      }
    },

    async appDelete() {
      const { code } = await api.application(this).appDelete(this.app_id);
      if (code === 0) {
        this.$message.success("操作成功");
        this.app_id = "";
        this.visibility = false;
        this.applicationList();
      }
    },
  },
  created() {
    this.appGroupList();
    this.modelList();
    this.organizationList();
    let permission = JSON.parse(localStorage.getItem("permission"));
    let curMenu = permission.find(item => item.txt === "应用管理")
    this.btnPermiss = curMenu.btns
  },
};
</script>

<style lang="stylus">
.Application {
  .page-head {
    padding: 0px !important;
  }

  .el-scrollbar__wrap {
    margin-top: getPx(-3) !important;
  }
}
</style>